import Vue from 'vue'
import qs from 'qs'
import { hasClass } from '@/global/utils/index'

/**
* el-table导出为excel文件
* fileName：导出成功后的文件名称，不包括.xls扩展名
*/
Vue.directive('table-toxls', {
    bind(el, binding, vnode) {
        const tableToXls = () => {
            const tb = document.querySelector('#' + binding.expression) || document.querySelector('.' + binding.expression)
            if (tb === null) {
                vnode.context.$alert('找不到待导出的表。', '操作提示', { type: 'warning' })
            }

            const titles = []// 标题，支持标题行合并
            if (tb.querySelectorAll('.el-table__header THEAD').length > 0) {
                const trs = tb.querySelector('.el-table__header THEAD').querySelectorAll('TR')
                for (let j = 0; j < trs.length; j++) {
                    const title = []// 标题行

                    const ths = trs[j].cells
                    for (let i = 0; i < ths.length; i++) {
                        const th = ths[i]
                        let align = 'left'
                        if (hasClass(th, 'is-center')) {
                            align = 'center'
                        } else if (hasClass(th, 'is-right')) {
                            align = 'right'
                        }
                        if (!hasClass(th, 'column_operate') && !hasClass(th, 'gutter')) {
                            title.push({ 'title': th.textContent, 'width': th.offsetWidth <= 250 ? th.offsetWidth : 250, 'align': align, 'colspan': th.colSpan, 'rowspan': th.rowSpan })
                        }
                    }

                    titles.push(title)
                }
            } else {
                const title = []// 标题行

                const ths = tb.querySelectorAll('TH')
                for (let i = 0; i < ths.length; i++) {
                    const th = ths[i]
                    let align = 'left'
                    if (hasClass(th, 'is-center')) {
                        align = 'center'
                    } else if (hasClass(th, 'is-right')) {
                        align = 'right'
                    }

                    if (!hasClass(th, 'column_operate') && !hasClass(th, 'gutter')) {
                        title.push({ 'title': th.textContent, 'width': th.offsetWidth <= 250 ? th.offsetWidth : 250, 'align': align, 'colspan': th.colSpan, 'rowspan': th.rowSpan })
                    }
                }

                titles.push(title)
            }

            const rows = []// 数据集
            const tableBodyWrapper = tb.querySelector('.el-table__body-wrapper')
            const trs = tableBodyWrapper !== undefined ? tableBodyWrapper.querySelectorAll('.el-table__row') : tb.querySelectorAll('.el-table__row')

            for (let i = 0; i < trs.length; i++) {
                const row = []// 数据行

                const tr = trs[i]
                if (tr.innerText !== '暂无数据') {
                    const tds = tr.cells
                    for (let j = 0; j < tds.length; j++) {
                        const td = tds[j]
                        let align = 'left'
                        if (hasClass(td, 'is-center')) {
                            align = 'center'
                        } else if (hasClass(td, 'is-right')) {
                            align = 'right'
                        }
                        if (!hasClass(td, 'column_operate')) {
                            row.push({ 'value': td.textContent, 'width': td.offsetWidth <= 250 ? td.offsetWidth : 250, 'align': align, 'colspan': td.colSpan, 'rowspan': td.rowSpan })
                        }
                    }
                    if (row.length > 0) {
                        rows.push(row)
                    }
                }
            }

            if (rows.length === 0) {
                vnode.context.$alert('没有可导出的数据！', '提示', { type: 'warning' })
                return
            }

            const attr = vnode.data.attrs
            let fileName = attr.fileName || attr['file-name']
            if (fileName === undefined) {
                fileName = document.querySelector('.el-header').innerText
            }
            vnode.context.$http({
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' },
                data: qs.stringify({ 'rows': JSON.stringify(rows), 'titles': JSON.stringify(titles), 'fileName': fileName }),
                url: 'common/exportXlsFile?httpPort=' + location.port
            }).then(res => {
                if (res.code === 'success') {
                    window.open(encodeURI(process.env.VUE_APP_BASE_API + '/' + res.body.xlsurl), '_blank')
                } else {
                    vnode.context.$alert(res.message, '操作提示', { type: 'error' })
                }
            })
        }

        el.removeEventListener('click', tableToXls)
        el.addEventListener('click', tableToXls)
    }
})

